﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LearnWPF.Controls
{
    /// <summary>
    /// Clock.xaml 的交互逻辑
    /// </summary>
    public partial class Clock : UserControl
    {
       
        public Clock()
        {
            InitializeComponent();
            this.Loaded += Clock_Loaded;
        }

        private void Clock_Loaded(object sender, RoutedEventArgs e)
        {
            DrawImage();
        }

        private void DrawImage()
        {
            DrawingGroup group = new DrawingGroup();
            using (DrawingContext ctx = group.Open())
            {
                DrawImageByContext(ctx);
            }
            group.Freeze();
            DrawingImage drawimage = new DrawingImage(group);
            this.imageBitmap.Source = drawimage;
        }

        private void DrawImageByContext(DrawingContext ctx)
        {
            int PicWidth = 500;
            int PicHeight = 500;          
            ctx.DrawRectangle(Brushes.Transparent, null, new Rect(0, 0, PicWidth, PicHeight));

            ctx.DrawEllipse(Brushes.DarkGray, null, new Point(250,250), 210, 210);
            ctx.DrawRectangle(Brushes.Black, null, new Rect(60,200,380,120));
                       
            string text = $"{Time.Hour:D2}:{Time.Minute:D2}:{Time.Second:D2}";
            FormattedText textUnit = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(new FontFamily("宋体"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 80, Brushes.LightGreen);
            ctx.DrawText(textUnit, new Point(80, 220));
        }

        /// <summary>
        /// Time
        /// </summary>
        public DateTime Time
        {
            get { return (DateTime)GetValue(TimeProperty); }
            set { SetValue(TimeProperty, value); }
        }
        public static readonly DependencyProperty TimeProperty =
        DependencyProperty.Register("Time", typeof(DateTime), typeof(Clock), new UIPropertyMetadata(DateTime.Now, TimePropertyChanged));

        private static void TimePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs arg)
        {
            Clock control = obj as Clock;
            control.DrawImage();
        }
    }
}
